import React, { useMemo, useState } from 'react';
import { Spin, message } from 'antd';
import { isOriginSource } from '../utils';

/**
 * 资源预览
 * @param {string} title - iframe 标题
 * @param {string} width - iframe 宽度
 * @param {string} height - iframe 高度
 * @param {boolean} visible - 是否展示
 * @param {string} origin - 以http或https开头的远端资源
 * @param {boolean} encode - 是否需要解码
 * @callback onError - 错误回调
 */
const OfficePreview = ({ title, width = '100%', height = '100%', visible, origin, onError, encode }) => {
    const [loading, setLoading] = useState(false);

    const endLoading = () => {
        setLoading(false);
    };

    const previewUrl = useMemo(() => {
        const handleError = () => {
            const errorMsg = '文件格式不支持!';
            if (onError) {
                onError(errorMsg);
            } else {
                message.error(errorMsg);
            }
            endLoading();
        };

        if (origin) {
            if (isOriginSource(origin)) {
                return `https://view.officeapps.live.com/op/view.aspx?src=${
                    encode ? encodeURIComponent(origin) : origin
                }`;
            }
            handleError();
        }
        return null;
    }, [encode, onError, origin]);

    return (
        previewUrl &&
        visible && (
            <>
                <iframe title={title} onLoad={endLoading} style={{ width, height, border: 0 }} src={previewUrl} />
                <Spin spinning={loading} />
            </>
        )
    );
};

export default OfficePreview;
